package com.hp.common_api.util;


import com.hp.common_api.entity.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * JWT工具类
 */
public class JwtUtil {

    public static final String JWT_KEY_USERNAME = "username";
    public static final String JWT_KEY_PASSWORD = "password";
    public static final String JWT_KEY_AUTHORITIES = "authorities";
    public static final int EXPIRE_MINUTES = 30;

    /**
     * 私钥加密token
     */
    public static String generateToken(String username,String password,String authorities, PrivateKey privateKey, int expireMinutes) throws Exception {
        return Jwts.builder()
                .claim(JWT_KEY_USERNAME, username)
                .claim(JWT_KEY_PASSWORD, password)
                .claim(JWT_KEY_AUTHORITIES, authorities)
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }

    /**
     * 从token解析用户
     * @param token
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static UserInfo getUserInfoFromToken(String token, PublicKey publicKey) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        String username = (String) body.get(JWT_KEY_USERNAME);
        UserInfo user = new UserInfo();
        user.setUsername(username);
        return user;
    }
}
